/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.zhongketech.sunflower.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zhongketech.sunflower.Constant;
import com.zhongketech.sunflower.MyApplication;
import com.zhongketech.sunflower.MyToast;
import com.zhongketech.sunflower.R;
import com.zhongketech.sunflower.app.AppManager;
import com.zhongketech.sunflower.control.SpecialNumsManager;
import com.zhongketech.sunflower.domain.User;
import com.zhongketech.sunflower.droidwall.DroidWallHandle;
import com.zhongketech.sunflower.sv.ScreenObserver;
import com.zhongketech.sunflower.sv.ScreenObserver.ScreenStateListener;
import com.zhongketech.sunflower.sv.SvManager;
import com.zhongketech.sunflower.transport.Action;
import com.zhongketech.sunflower.transport.LogUtil;
import com.zhongketech.sunflower.transport.im.ZKSocket;
import com.zhongketech.sunflower.transport.model.Authorizations;
import com.zhongketech.sunflower.transport.model.SpecialNums;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;


/**
 * 登陆页面
 * 
 */
public class LoginActivity extends BaseActivity {
	private static final String TAG = "LoginActivity";
	private static final int LOGIN_SUCC = 0;
	private Context context ;

	private EditText usernameEditText;
	private EditText passwordEditText;

	private boolean progressShow;
	private Handler handler;
	private boolean isUploadApp = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);


		setContentView(R.layout.activity_login);
		//		screenHandle();
		usernameEditText = (EditText) findViewById(R.id.username);
		passwordEditText = (EditText) findViewById(R.id.password);
		//		DroidWallHandle.getInstance(MyApplication.getInstance().getApplicationContext()).diableNetLock();
		context = this;

		// 如果用户名改变，清空密码
		usernameEditText.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				passwordEditText.setText(null);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

		handler = new Handler() {
			public void handleMessage(Message msg) {
				if(null != msg)
				{
					switch (msg.arg1) {
					case LOGIN_SUCC:
						SvManager.getInstance().check();
						Intent intent = getIntent();
						intent.setClass(context, MainActivity.class);
						startActivity(intent);
						if(isUploadApp)
						{
							AppManager.getInstance().uploadapp();
							isUploadApp = false;
						}
						finish();

						//					
						break;

					default:
						break;
					}
				}
			}
		};

	}

	//	private void screenHandle()
	//	{
	//		ScreenObserver screenObserver = new ScreenObserver(this);
	//		screenObserver.requestScreenStateUpdate(new ScreenStateListener() {
	//			
	//			@Override
	//			public void onScreenOn() {
	//				// TODO Auto-generated method stub
	//				MyToast.getInstance().show("开始使用手机");
	//			}
	//			
	//			@Override
	//			public void onScreenOff() {
	//				// TODO Auto-generated method stub
	//				MyToast.getInstance().show("停止使用手机");
	//			}
	//		});
	//	}

	/**
	 * 登陆
	 * 
	 * @param view
	 */
	public void login(View view) {
		//		if (!CommonUtils.isNetWorkConnected(this)) {
		//			Toast.makeText(this, R.string.network_isnot_available, Toast.LENGTH_SHORT).show();
		//			return;
		//		}
		final String username = usernameEditText.getText().toString();
		final String password = passwordEditText.getText().toString();
		if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {
			progressShow = true;

			isUploadApp = true;
			authorizations(username,password);

			// 调用sdk登陆方法登陆聊天服务器
			//			EMChatManager.getInstance().login(username, password, new EMCallBack() {
			//
			//				@Override
			//				public void onSuccess() {
			//					if (!progressShow) {
			//						return;
			//					}
			//					// 登陆成功，保存用户名密码
			//					DemoApplication.getInstance().setUserName(username);
			//					DemoApplication.getInstance().setPassword(password);
			//					runOnUiThread(new Runnable() {
			//						public void run() {
			//							pd.setMessage("正在获取好友和群聊列表...");
			//						}
			//					});
			//					try {
			//						// demo中简单的处理成每次登陆都去获取好友username，开发者自己根据情况而定
			//						List<String> usernames = EMChatManager.getInstance().getContactUserNames();
			//						Map<String, User> userlist = new HashMap<String, User>();
			//						for (String username : usernames) {
			//							User user = new User();
			//							user.setUsername(username);
			//							setUserHearder(username, user);
			//							userlist.put(username, user);
			//						}
			//						// 添加user"申请与通知"
			//						User newFriends = new User();
			//						newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
			//						newFriends.setNick("申请与通知");
			//						newFriends.setHeader("");
			//						userlist.put(Constant.NEW_FRIENDS_USERNAME, newFriends);
			//						// 添加"群聊"
			//						User groupUser = new User();
			//						groupUser.setUsername(Constant.GROUP_USERNAME);
			//						groupUser.setNick("群聊");
			//						groupUser.setHeader("");
			//						userlist.put(Constant.GROUP_USERNAME, groupUser);
			//
			//						// 存入内存
			//						DemoApplication.getInstance().setContactList(userlist);
			//						// 存入db
			//						UserDao dao = new UserDao(LoginActivity.this);
			//						List<User> users = new ArrayList<User>(userlist.values());
			//						dao.saveContactList(users);
			//
			//						// 获取群聊列表,sdk会把群组存入到EMGroupManager和db中
			//						EMGroupManager.getInstance().getGroupsFromServer();
			//					} catch (Exception e) {
			//						e.printStackTrace();
			//					}
			//
			//					if (!LoginActivity.this.isFinishing())
			//						pd.dismiss();
			//					// 进入主页面
			//					startActivity(new Intent(LoginActivity.this, MainActivity.class));
			//					finish();
			//				}
			//
			//				@Override
			//				public void onProgress(int progress, String status) {
			//
			//				}
			//
			//				@Override
			//				public void onError(int code, final String message) {
			//					if (!progressShow) {
			//						return;
			//					}
			//					runOnUiThread(new Runnable() {
			//						public void run() {
			//							pd.dismiss();
			//							if (message.indexOf("not support the capital letters") != -1) {
			//								Toast.makeText(getApplicationContext(), "用户名不支持大写字母", 0).show();
			//							} else {
			//								Toast.makeText(getApplicationContext(), "登录失败: " + message, 0).show();
			//							}
			//
			//						}
			//					});
			//				}
			//			});
		}
	}

	/**
	 * 注册
	 * 
	 * @param view
	 */
	public void register(View view) {
		startActivityForResult(new Intent(this, RegisterActivity.class), 0);
	}

	@Override
	protected void onResume() {
		super.onResume();
		//		if (DemoApplication.getInstance().getUserName() != null) {
		//			usernameEditText.setText(DemoApplication.getInstance().getUserName());
		//		}

		// 如果用户名密码都有，直接进入主页面
		if (null != MyApplication.getInstance().getPhone() && null != MyApplication.getInstance().getPassword()) {

			//			//			final ProgressDialog pd = new ProgressDialog(this);
			//			//			pd.setMessage("正在登录...");
			//			//			pd.show();
			//			new Thread(new Runnable() {
			//				public void run() {
			//					Looper.prepare();
			//					// 调用sdk注册方法
			//					Authorizations az = new Action().authorizations(MyApplication.getInstance().getPhone(),MyApplication.getInstance().getPassword());
			//
			//					if(null != az)
			//					{
			//						MyApplication.getInstance().setId(az.getId());
			//						MyApplication.getInstance().setSessionToken(az.getSession_token());
			//						MyApplication.getInstance().setPhone(az.getPhone());
			//						MyApplication.getInstance().setVisibleId(az.getVisible_id());
			//
			//						//						pd.dismiss();
			//						MyToast.getInstance().show("登录成功");
			//						finish();
			//					}
			//					else
			//					{
			//						MyToast.getInstance().show("登录失败:"+MyApplication.getInstance().getPhone());
			//					}
			//				}
			//			}).start();
			//			
			//			
			//
			//			startActivity(new Intent(this, MainActivity.class));
			//			finish();

			authorizations(MyApplication.getInstance().getPhone(),MyApplication.getInstance().getPassword());
		}
	}


	private boolean authorizations(final String username,final String password)
	{
		final ProgressDialog pd = new ProgressDialog(LoginActivity.this);
		pd.setCanceledOnTouchOutside(false);
		pd.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				progressShow = false;
			}
		});

		pd.setMessage("正在登陆...");
		pd.show();

		new Thread(new Runnable() {
			public void run() {
				Looper.prepare();
				Authorizations az = new Action().authorizations(username,password);
				pd.dismiss();

				if(null != az)
				{
					MyApplication.getInstance().setId(az.getId());
					MyApplication.getInstance().setSessionToken(az.getSession_token());
					//						ZKSocket.getInstance().handshake(az.getId(), az.getSession_token());
					MyApplication.getInstance().setPhone(az.getPhone());
					MyApplication.getInstance().setPassword(password);
					MyApplication.getInstance().setVisibleId(az.getVisible_id());
					MyApplication.getInstance().setRole(az.getRole());
					MyApplication.getInstance().setBirthday(az.getBirthday());
					MyApplication.getInstance().setGender(az.getGender());
					MyApplication.getInstance().setName(az.getName());
					MyApplication.getInstance().setAvatar_url(az.getAvatar_url());

					//和tcp服务器握手
					
//					ZKSocket zkSocket = ZKSocket.getInstance();
//					if(null != zkSocket)
//					{
//						zkSocket.handshake(az.getId(), az.getSession_token());
//					}
//					else
//					{
//						MyToast.getInstance().show("TCP连接服务器失败");
//					}
//					

					MyToast.getInstance().show("登录成功");
					final Message msg = new Message();
					msg.arg1 = LOGIN_SUCC;
					handler.sendMessage(msg);

					SpecialNumsManager.save(null);
				}
				else
				{
					MyToast.getInstance().show("登录失败:"+MyApplication.getInstance().getPhone());
					return;
				}
				
			}
		}).start();

		return false;
	}

	/**
	 * 设置hearder属性，方便通讯中对联系人按header分类显示，以及通过右侧ABCD...字母栏快速定位联系人
	 * 
	 * @param username
	 * @param user
	 */
	protected void setUserHearder(String username, User user) {
		//		String headerName = null;
		//		if (!TextUtils.isEmpty(user.getNick())) {
		//			headerName = (String) user.getNick();
		//		} else {
		//			headerName = user.getUsername();
		//		}
		//		if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
		//			user.setHeader("");
		//		} else if (Character.isDigit(headerName.charAt(0))) {
		//			user.setHeader("#");
		//		} else {
		//			//user.setHeader(HanziToPinyin.getInstance().get(headerName.substring(0, 1)).get(0).target.substring(0, 1).toUpperCase());
		//			char header = user.getHeader().toLowerCase().charAt(0);
		//			if (header < 'a' || header > 'z') {
		//				user.setHeader("#");
		//			}
		//		}
	}

}
